import { Form, FormInstance, Input, Modal, Radio, Select, Spin, message } from "antd";
import { PropsTypes, USerDataSourceFace } from "./type";
import { useEffect, useState } from "react";
import React from "react";
import { ceatUser, UpDataUser } from "@/api/user"
import { cloneDeep } from "lodash";
import checkPasswordRule from "@/utils/checkPassWord";
import { valifyPhone } from "@/utils/verify"
import { encrypt } from "@/utils/rsa";
import { useSelector } from "react-redux"
import { userState } from "@/store/user/types";
const Model: React.FC<PropsTypes> = (props) => {
    const { user } = useSelector((state: { user: userState }) => ({
        user: state.user,
    }))
    const options = cloneDeep(user.shopsOptions.map((e: any) => {
        e.value = e.uuid
        e.label = e.shopName
        return e
    }))
    const [titel,setTitel] = useState("新增用户")
    const validatePass = (_rule: any, value: any) => {
        const v = formRef?.current?.getFieldValue("account")
        if (!value) {
            if (props.upData?.uuid) {
                return Promise.resolve()
            } else {
                return Promise.reject('请输入密码')
            }

        } else {
            const bad = checkPasswordRule(value, v);
            if (bad) {
                return Promise.reject('密码不符合规则' + bad)
            } else {
                return Promise.resolve()
            }
        }
    };
    const validateCkPass = (_rule: any, value: any) => {
        const v = formRef?.current?.getFieldValue("passWord")
        if (v && value !== v) {
            return Promise.reject('两次输入的密码不一致')
        }
        else {
            return Promise.resolve()
        }
    }
    const [loading, setLoading] = useState(false)
    const [state, setState] = useState<USerDataSourceFace>({
        uuid: "",
        account: "", // 账号
        nickName: "", // 昵称
        phone: "", // 联系方式
        sex: "", // 性别
        updateTime: "", // 跟新时间
        shops: [], // 绑定店铺
        address: "",
        passWord: "",
        ckPassWord: ""
    })
    const formRef = React.useRef<FormInstance>(null);
    const handleOk = async () => {
        const validata: USerDataSourceFace = await formRef?.current?.validateFields()
        if (validata) {
            setLoading(true)
            if (props.upData?.uuid) {
                const data = { ...cloneDeep(props.upData), ...validata }
                const d = cloneDeep(data) as any
                if (d.passWord) {
                    d.passWord = encrypt(d.passWord) || ""
                }
                if (d.shops.length > 0) {
                    d.shops = d.shops.join(",")
                }
                delete d.ckPassWord
                UpDataUser([d]).then(() => {
                    message.success("修改成功")
                    close(true)
                }).catch(() => {
                }).finally(() => {

                    setLoading(false)
                })


            } else {
                const d = cloneDeep(validata) as any
                if (d.passWord) {
                    d.passWord = encrypt(d.passWord) || ""
                }
                if (d.shops.length > 0) {
                    d.shops = d.shops.join(",")
                }
                delete d.ckPassWord
                await ceatUser(d)
                    .then(() => {
                        message.success("添加成功")
                        close(true)
                    }).catch(() => {
                        message.error("添加失败")
                    }).finally(() => {

                        setLoading(false)
                    })
            }


        }

    }
    const handleCancel = () => {
        close(false)
    }
    const close = (loadList: boolean) => {
        props.changeShow(false, loadList)
        setState({
            uuid: "",
            account: "",  // 账号
            nickName: "", // 昵称
            phone: "", // 联系方式
            sex: "", // 性别
            updateTime: "",  // 跟新时间
            shops: [], // 绑定店铺
            address: "",
            passWord: "",
            ckPassWord: ""
        })
    }
    const reule = () => {
        if (!props.upData?.uuid) {
            return {
                pass: [{ required: true, validator: validatePass }],
                ckpass: [{ required: true, validator: validateCkPass }]
            }
        } else {
            return {
                pass: [{ validator: validatePass }],
                ckpass: [{ validator: validateCkPass }]
            }
        }

    }
    useEffect(() => {
        if (props.upData) {
            formRef?.current?.setFieldsValue({
                ...props.upData,
                passWord: "",
                ckPassWord: ""
            })
            
        }
        if (props.upData?.uuid){
            setTitel("编辑用户")
        }else{
            setTitel("新增用户")
        }
    }, [props.upData])
    return (
        <Modal title={titel} open={props.show} onOk={handleOk} onCancel={handleCancel}>
            <Spin spinning={loading}>
                <Form
                    name="basic"
                    labelCol={{ span: 6 }}
                    initialValues={{ shops: [...state.shops] }}
                    autoComplete="off"
                    ref={formRef}
                >
                    <Form.Item<USerDataSourceFace>
                        label="用户名"
                        name="account"
                        rules={[{ max: 12 }, { required: true, message: '请输入用户名!' }]}
                    >
                        <Input disabled={!!props.upData?.uuid} />
                    </Form.Item>
                    <Form.Item<USerDataSourceFace>
                        label="密码"
                        name="passWord"
                        rules={[...reule().pass]}
                    >
                        <Input.Password />
                    </Form.Item>
                    <Form.Item<USerDataSourceFace>
                        label="再次输入密码"
                        name="ckPassWord"
                        rules={[
                            ...reule().ckpass
                        ]}
                    >
                        <Input.Password />
                    </Form.Item>
                    <Form.Item<USerDataSourceFace>
                        label="用户昵称"
                        name="nickName"
                        rules={[{ max: 12 }, { required: true, message: '请输入用户昵称!' }]}
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item<USerDataSourceFace>
                        label="手机号"
                        name="phone"
                        rules={[{ max: 11 }, { required: true, validator: valifyPhone }]}
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item label="性别" name="sex" rules={[{ required: true, message: '请选择性别!' }]}>
                        <Radio.Group>
                            <Radio value="男"> 男 </Radio>
                            <Radio value="女"> 女 </Radio>
                        </Radio.Group>
                    </Form.Item>
                    <Form.Item<USerDataSourceFace>
                        label="地址"
                        name="address"
                        rules={[{ required: true, message: '请输入地址!' }]}
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item<USerDataSourceFace>
                        label="绑定店铺"
                        name="shops"
                        rules={[{ required: true, message: '请绑定店铺' }]}
                    >
                        <Select
                            mode="multiple"
                            style={{ width: '100%' }}
                            placeholder="请绑定店铺"
                            options={options}
                        />
                    </Form.Item>
                </Form>
            </Spin>

        </Modal>
    )
}
export default Model